import type { FormItemDto } from '../types'
import { Component, Prop, Emit, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import { type AnyObject } from '@/types'
import type { FormItemContext } from 'ant-design-vue/es/form/FormItemContext'
import { Input, message, Tooltip } from 'ant-design-vue'
import { useForm } from 'ant-design-vue/es/form'
import { CheckCircleFilled, CloseCircleFilled, DeleteFilled, PlusOutlined } from '@ant-design/icons-vue'
import type { InputRef } from 'ant-design-vue/es/vc-input/inputProps'

export interface TagDto {
    value: string
    color: string
    bgColor: string
    editable?: boolean
}

@Component({
    emits: ['click']
})
export class AddTag extends Render {
    formItem = undefined as FormItemContext | undefined

    tagList = [] as TagDto[]

    history = [] as TagDto[]

    @Prop() itemData?: FormItemDto

    @Prop() modelValue?: string

    @Emit('update:modelValue')
    handleEmitData(value: TagDto[]) {
        return value
    }

    @Emit('click')
    handleClicked() {}

    @Watch('modelValue', { immediate: true })
    watchModelValue(newValue: TagDto[]) {
        if (newValue) {
            this.tagList = newValue
        }
    }

    inputRefs = {} as AnyObject

    // 色盘的颜色，需要在windi.config里的safelist里配置一下不然不能动态的获取颜色
    colorPans = ['#6cea6a', '#52acff', '#9666ff', '#ff7e4c', '#2f343e']

    setRefs(ev: any, index: number) {
        if (ev?.input) {
            this.inputRefs[`input${index}`] = ev.input
        }
    }

    getStyle(color: string) {
        return color
    }

    // 获取默认颜色 如果有标签要避开已有标签的颜色
    setDefaultColor() {
        const tempColorPans = [] as string[]
        this.colorPans.forEach(i => {
            if (this.tagList.every(color => i !== color.bgColor)) {
                tempColorPans.push(i)
            }
        })
        return tempColorPans[0]
    }

    handleAdd() {
        if (this.itemData?.params?.limit && this.tagList.length >= this.itemData.params.limit) {
            message.error(`最多只能添加${this.itemData?.params?.limit}个标签`)
            return
        }
        this.tagList.push({
            editable: true,
            bgColor: this.setDefaultColor(),
            value: '',
            color: '#ffffff'
        })
        setTimeout(() => {
            this.inputRefs[`input${this.tagList.length-1}`].focus()
        }, 100)
    }

    onHandleConfirm(data: TagDto, index: number) {
        if (!data.value.trim()) {
            this.tagList.splice(index, 1)
        } else {
            data.editable = false
        }
        this.emitData()
    }

    emitData() {
        if (this.tagList.length) {
            const res = this.tagList.map((i) => {
                return {
                    value: i.value,
                    color: i.color,
                    bgColor: i.bgColor
                }
            })
            this.setHistoryTag()
            this.handleEmitData(res)
        }
    }

    setHistoryTag() {
        this.tagList.forEach(i => {
            if(this.history.every(h => h.value !== i.value || h.bgColor !== i.bgColor)) {
                console.log(i)
                this.history.unshift(i)
            }
        })
        const newHistory = this.history.slice(0, (this.itemData?.params?.maxHistoryLength ?? 15))
        localStorage.setItem(this.itemData?.params?.historyName, JSON.stringify(newHistory))
    }

    onColorSelect(item: TagDto, color: string, index: number) {
        item.bgColor = color
        this.inputRefs[index]?.focus()
    }

    onEditItem(data: TagDto) {
        data.editable = true
    }

    onRemoveTag(index: number) {
        this.tagList.splice(index, 1)
    }

    onRemoveHistoryTag(event: any, item: TagDto, index: number) {
        event.cancelBubble = true
        this.history.splice(index, 1)
        localStorage.setItem(this.itemData?.params?.historyName, JSON.stringify(this.history))
    }

    onHistoryClick(item: TagDto) {
        if (this.itemData?.params?.limit && this.tagList.length >= this.itemData.params.limit) {
            message.error(`最多只能添加${this.itemData?.params?.limit}个标签`)
            return
        }
        if (this.tagList.every(i => i.value !== item.value || i.bgColor !== item.bgColor)) {
            this.tagList.push(item)
            this.emitData()
        }
    }

    render() {
        if (this.itemData?.params?.showHistory && this.itemData?.params?.historyName && localStorage.getItem(this.itemData?.params?.historyName)) {
            this.history = JSON.parse(localStorage.getItem(this.itemData?.params?.historyName) as string)
        }
        return (<>
            <div>
                {this.itemData?.params?.prefix && <div>{this.itemData.params.prefix}</div>}
                <div class="flex">
                    <div
                        onClick={this.handleAdd}
                        class="border-1 cursor-pointer border-dashed py-0.25 px-8 flex items-center rounded-sm mr-16"
                    >
                        <PlusOutlined />
                        <span class="ml-4">添加标签</span>
                    </div>
                    {this.tagList.map((i, index) => {
                        return i.editable ? (
                            <div class="bg-white py-0.25 px-8 flex items-center rounded-sm mr-16 relative">
                                <Input
                                    ref={(el) => this.setRefs(el, index)}
                                    v-model={i.value}
                                    maxlength={this.itemData?.params?.maxLen}
                                    placeholder={`${this.itemData?.params?.maxLen ? `最多${this.itemData?.params?.maxLen}个字`: '请输入'}`}
                                />

                                <div class="flex items-center absolute top-1/2 transform -translate-y-1/2 right-9 mt-0.5">
                                    <div class="text-blue-default cursor-pointer mr-1" onClick={() => this.onHandleConfirm(i, index)}>
                                        <CheckCircleFilled />
                                    </div>
                                    <div class="text-error cursor-pointer" onClick={() => this.onHandleConfirm(i, index)}>
                                        <CloseCircleFilled />
                                    </div>
                                </div>

                                <Tooltip placement="top" v-slots={{
                                    content: () => {
                                        return <div class="flex gap-4.5 p-16">
                                            {
                                                this.colorPans.map(color => {
                                                    return <div onClick={() => this.onColorSelect(i, color, index)} class={`cursor-pointer w-12 h-12 rounded-full bg-[${color}]`}></div>                                    
                                                })
                                            }
                                        </div>
                                    }
                                }}>
                                    <div class={`cursor-pointer absolute top-1/2 transform -translate-y-1/2 right-4.5 w-12 h-12 rounded-full bg-[${[this.getStyle(i.bgColor)]}]`}></div>
                                </Tooltip>
                            </div>
                        ) : (
                            <div class={`bg-[${i.bgColor}] text-white py-0.25 px-8 flex items-center rounded-sm mr-16`}>
                                <div onClick={() => this.onRemoveTag(index)} class="mt-0.5">
                                    <CloseCircleFilled class="cursor-pointer" />
                                </div>
                                <span
                                    onDblclick={() => this.onEditItem(i)}
                                    class="ml-4 cursor-pointer"
                                >
                                    {i.value}
                                </span>
                            </div>
                        )
                    })}
                </div>
                {this.itemData?.params?.suffix && <div>{this.itemData.params.suffix}</div>}
            </div>
            {
                (this.itemData?.params?.showHistory && this.history?.length) ?
                    this.history.map((i: TagDto, index: number) => {
                        return <div class={`bg-[${i.bgColor}] text-[${i.color}] inline-block px-8 rounded-sm mr-8 mb-8 cursor-pointer`}>
                            <div class="flex group transition-all" onClick={() => this.onHistoryClick(i)}>
                                <div>{i.value}</div>
                                <div class="ml-8 hidden group-hover:block" onClick={() => this.onRemoveHistoryTag(event, i, index)}>
                                    <DeleteFilled />
                                </div>
                            </div>
                        </div>
                    }) : <></>
            }
        </>

        )
    }
}

export default toNative<
    {},
    { click: (data: any) => void }>(AddTag)
